package org.hry.netty.udp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;


/**
 * @Desc
 * @Author houruiyang
 * @Date 2022/2/17
 **/
public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        System.out.println("客户端接收到消息：" + packet.content().toString(StandardCharsets.UTF_8));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端初始化");
        // 往指定端口发送数据
        InetSocketAddress address = new InetSocketAddress("255.255.255.255", 8000);
        ByteBuf byteBuf = Unpooled.copiedBuffer("来自客户端的信息".getBytes(StandardCharsets.UTF_8));
        ctx.writeAndFlush(new DatagramPacket(byteBuf, address)).sync();
    }
}
